package com.niji.littly_donkey_android.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.*;
import android.util.Log;
import android.view.*;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.*;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import com.android.volley.*;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.niji.littly_donkey_android.R;
import com.niji.littly_donkey_android.adapter.IndexCommentAdapter;
import com.niji.littly_donkey_android.adapter.IndexVideoAdapter;
import com.niji.littly_donkey_android.adapter.MyViewPagerAdapter;
import com.niji.littly_donkey_android.bean.Comment;
import com.niji.littly_donkey_android.bean.Fans;
import com.niji.littly_donkey_android.bean.Video;
import com.niji.littly_donkey_android.http.ConnectViaSession;
import com.niji.littly_donkey_android.util.EntityUtils;
import com.niji.littly_donkey_android.util.JsonUtil;
import com.niji.littly_donkey_android.util.NetworkGlideImageLoader;
import com.niji.littly_donkey_android.util.UrlUtil;
import com.niji.littly_donkey_android.view.CircleImageView;
import com.niji.littly_donkey_android.view.PopupWindowManager;
import com.niji.littly_donkey_android.view.VerticalViewPager;
import org.json.JSONException;

import java.net.FileNameMap;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class IndexActivity extends AppCompatActivity {

    private static final String TAG = "IndexActivity";

    private Button index_my_information;

    private Button index_my_commission;

    private Button index_want_go;

    private CircleImageView img_head;

    private ImageView img_heart;

    private VideoView index_video;

    private TextView index_video_id;

    private ImageView index_guanzhu_img;

    private ImageView index_tuijian_img;

    private ListView video_list;

    private RelativeLayout index_main;

    private TextView text_follow;

    private TextView text_recommend;

    private CircleImageView index_music;

    private static Integer index = 0;

    private static Integer attractions_id = -1;

    private static ArrayList<Map<String,Object>> videoList;

    private static ArrayList<Comment> parentComment ;

    private static ArrayList<Comment> childComments ;

    private static int commentNumber = 0;

    private static Boolean is_attention = false;

    private static int user_id = -1 ;

    private static int video_id = -1;

    private Button img_share;

    boolean isExit;

    private ListView index_comment_listview;

    private Context context;

    private RelativeLayout index_loading;

    private static String videoUrl;

    @Override
    public void onCreate(final Bundle savedInstanceState) {
        checkPermission();
        super.onCreate(savedInstanceState);
        setContentView(R.layout.index_activaty);
        context = this;
        init();
        indexMyInformation();
        indexMyCommission();
        indexWantGo();
        imageHead();
        faublous();
//        MotionUpAndDown();
        changeMode();
        showComment();
        videoMethod();
        ShareVideo();
//        videoListMethed();
    }

//



//    @Override
//    protected void onResume() {
//        getVideoList(1);
//        super.onResume();
//    }

    /***
     * 上滑、下滑
     */
    float mPosX;
    float mPosY;
    float mCurPosX;
    float mCurPosY;
    long currentMS;
    private void MotionUpAndDown() {
        index_main = findViewById(R.id.index_main);
        RelativeLayout video_play = findViewById(R.id.video_play);

        index_main.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {

                    case MotionEvent.ACTION_DOWN:
                        mPosX = event.getX();
                        mPosY = event.getY();
                        currentMS = System.currentTimeMillis();//long currentMS     获取系统时间
                        break;
                    case MotionEvent.ACTION_MOVE:
                        mCurPosX = event.getX();
                        mCurPosY = event.getY();

                        break;
                    case MotionEvent.ACTION_UP:
                        long moveTime = System.currentTimeMillis() - currentMS;//移动时间
                        float Y=mCurPosY - mPosY;
                        float X=mCurPosX-mPosX;
                        if(((mCurPosY - mPosY) > 0) &&(Math.abs(mCurPosY - mPosY)> 50) && moveTime > 100) {
                            slideDown(); //改成自己想要执行的代码
                            return false;
                        }else if(((mCurPosY - mPosY) < 0) &&(Math.abs(mCurPosY - mPosY)> 50) && moveTime > 150){
                            slideUp();//改成自己想要执行的代码
                            return false;
                        }else {
                            if (index_video.isPlaying()){
                                video_play.setVisibility(View.VISIBLE);
                                index_video.pause();
                            }else {
                                video_play.setVisibility(View.INVISIBLE);
                                index_video.start();
                            }
                            return false;
                        }
                }
                return true;
            }



        });
    }

    /**
     * 视频播放暂停事件，重播
     */
    private void videoMethod() {
        index_video = findViewById(R.id.index_video);
        RelativeLayout video_play = findViewById(R.id.video_play);
        //设置循环播放
        index_video.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                mp.start();
                mp.setLooping(true);
            }
        });

    }

    /**
     * 评论按钮
     */
    private void showComment() {
        Button img_comment = findViewById(R.id.img_comment);
        img_comment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(video_id != -1){
                    getParentComment(video_id);
                }
                showPopupWindow(v);

            }
        });

    }

    /**
     * 显示
     *
     * @param targetView 需要显示的内容view
     * @return
     */
    public void showPopupWindow(View targetView) {
        // 一个自定义的布局，作为显示的内容
        View contentView = LayoutInflater.from(context).inflate(
                R.layout.dialog_comment, null);
        final PopupWindow popupWindow = new PopupWindow(contentView,
                ViewGroup.LayoutParams.MATCH_PARENT,  ViewGroup.LayoutParams.WRAP_CONTENT, true);

        popupWindow.setTouchable(true);

        Button cancel_comment = contentView.findViewById(R.id.cancel_comment);
        cancel_comment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });

//        popupWindow.setTouchInterceptor(new View.OnTouchListener() {
//
//            @Override
//            public boolean onTouch(View v, MotionEvent event) {
//
////                Log.i("mengdd", "onTouch : ");
//
//                return false;
//                // 这里如果返回true的话，touch事件将被拦截
//                // 拦截后 PopupWindow的onTouchEvent不被调用，这样点击外部区域无法dismiss
//            }
//        });
        // 如果不设置PopupWindow的背景，无论是点击外部区域还是Back键都无法dismiss弹框
        // 我觉得这里是API的一个bug
        popupWindow.setBackgroundDrawable(getResources().getDrawable(
                R.drawable.shape_top_round_white));
        if(attractions_id != -1){
            if(parentComment == null){
                RelativeLayout no_comment = contentView.findViewById(R.id.no_comment);
                no_comment.setVisibility(View.VISIBLE);
            }else {
                if(parentComment.size() == 0){
                    RelativeLayout no_comment = contentView.findViewById(R.id.no_comment);
                    no_comment.setVisibility(View.VISIBLE);
                }else {
                    RelativeLayout no_comment = contentView.findViewById(R.id.no_comment);
                    no_comment.setVisibility(View.GONE);
                    TextView index_comment_commentNum = contentView.findViewById(R.id.index_comment_commentNum);
                    index_comment_commentNum.setText("" + commentNumber + "条评论");
                    index_comment_listview = contentView.findViewById(R.id.index_comment_listview);
                    IndexCommentAdapter indexCommentAdapter = new IndexCommentAdapter(IndexActivity.this, parentComment);
                    index_comment_listview.setAdapter(indexCommentAdapter);
                }
            }

        }else {
            RelativeLayout no_comment = contentView.findViewById(R.id.no_comment);
            no_comment.setVisibility(View.VISIBLE);
        }
        // 设置好参数之后再show
        int[] location = new int[2];
        targetView.getLocationOnScreen(location);
        popupWindow.showAtLocation(targetView,Gravity.LEFT|Gravity.BOTTOM,0,-location[1]);


    }

    /**
     * 发送评论
     */
    private void sendComment(String commentContent) {
        EditText index_comment = findViewById(R.id.index_comment);
        if(!commentContent.equals("")){
            String url = UrlUtil.URL + "/user/comments/add";
            RequestQueue requestQueue= Volley.newRequestQueue(IndexActivity.this);
            StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
                @Override
                public void onResponse(String s) {
                    try {
                        Map<String, Object> map = JsonUtil.jsonToMap(s);
                        Integer code = (Integer) map.get("code");
                        if (code == 0) {
                            Toast.makeText(IndexActivity.this, "评论发表成功", Toast.LENGTH_LONG).show();
                            index_comment.setText("");
                            getVideo(index);
                        } else if(code == -1){
                            Toast.makeText(IndexActivity.this, "登录失效，请重新登录", Toast.LENGTH_LONG).show();
                            Intent intent = new Intent(IndexActivity.this, GetPhoneCodeActivity.class);
                            intent.putExtra("loginCode","-1");
                            startActivity(intent);
                            finish();
                        }else {
                            Object message = map.get("message");
                            Toast.makeText(IndexActivity.this, message.toString(), Toast.LENGTH_SHORT).show();
                            overridePendingTransition(R.anim.xpage_slide_in_left, R.anim.xpage_slide_out_right);
                            finish();
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {
                    Log.e(TAG, volleyError.getMessage(), volleyError);
                }
            }) {
                @Override
                protected Map<String, String> getParams() throws AuthFailureError {
                    HashMap<String, String> map = new HashMap<>();
                    map.put("video_id",String.valueOf(video_id));
                    map.put("content",commentContent);
                    return map;
                }

                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    String sesseionid = new ConnectViaSession(IndexActivity.this).GetSession();
                    if (!sesseionid.equals("")) {
                        HashMap<String, String> headers = new HashMap<String, String>();
                        headers.put("cookie", sesseionid);
                        return headers;
                    } else {
                        return super.getHeaders();
                    }
                }
            };

            requestQueue.add(stringRequest);
        }
    }


    /**
     * 切换关注
     *推荐
     */
    private void changeMode() {
        text_follow = findViewById(R.id.text_follow);
        text_recommend = findViewById(R.id.text_recommend);
        index_guanzhu_img = findViewById(R.id.index_guanzhu_img);
        index_tuijian_img = findViewById(R.id.index_tuijian_img);

        text_follow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                index_guanzhu_img.setVisibility(View.VISIBLE);
                index_tuijian_img.setVisibility(View.INVISIBLE);
                videoList = new ArrayList<>();
                getVideoList(2);
                index = 0;
                if(videoList != null && videoList.size() != 0){
                    getVideo(0);
                }
            }
        });

        text_recommend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                index_tuijian_img.setVisibility(View.VISIBLE);
                index_guanzhu_img.setVisibility(View.INVISIBLE);
                videoList = new ArrayList<>();
                getVideoList(1);
                index = 0;
                if(videoList != null && videoList.size() != 0){
                    getVideo(0);
                }
            }
        });


    }


    /***
     * 获取视频
     * @param
     */
    public void getVideo(int i){
        Map<String, Object> map = videoList.get(i);
        Integer id = (Integer) map.get("id");
        Integer user_id = (Integer) map.get("user_id");
        Integer attractions_id = (Integer) map.get("attractions_id");
        String title = (String) map.get("title");
        String url = (String) map.get("url");
        String cover = (String) map.get("cover");
        Integer likes = (Integer) map.get("likes");
        Integer comments = (Integer) map.get("comments");
        Integer shares = (Integer) map.get("shares");
        Integer commission = (Integer) map.get("commission");
        String remark = (String) map.get("remark");
        String province = (String) map.get("province");
        String city = (String) map.get("city");
        Boolean is_likes = (Boolean) map.get("is_likes");
        is_attention = (Boolean) map.get("is_attention");
        Map<String,Object> aPublic = (Map<String, Object>) map.get("publish");
        String nickname = (String) aPublic.get("nickname");
        String avatar = UrlUtil.URL +  (String) aPublic.get("avatar");
        String signature = (String) aPublic.get("signature");
        video_id = id;
        videoUrl = url;
        this.attractions_id = attractions_id;
        index_video_id = findViewById(R.id.index_video_id);
        TextView title_introduce = findViewById(R.id.text_introduce);
        TextView text_heartNum = findViewById(R.id.text_heartNum);
        TextView text_commentNum = findViewById(R.id.text_commentNum);
        TextView text_shareNum = findViewById(R.id.text_shareNum);
        TextView text_commission = findViewById(R.id.text_commission);
        ImageView text_commission_logo = findViewById(R.id.text_commission_logo);
        ImageView index_video_cover = findViewById(R.id.index_video_cover);
        TextView text_name = findViewById(R.id.text_name);
        index_video = findViewById(R.id.index_video);
        text_name.setText("@" + nickname);
        index_video_cover.setVisibility(View.VISIBLE);
        NetworkGlideImageLoader.getInstance().displayImage(IndexActivity.this,avatar,img_head,0,0);
        NetworkGlideImageLoader.getInstance().displayImage(IndexActivity.this,(UrlUtil.URL + cover),index_video_cover,0,0);
        NetworkGlideImageLoader.getInstance().displayImage(IndexActivity.this,avatar,index_music,0,0);
        if (is_likes){
            img_heart.setBackground(getDrawable(R.mipmap.smallheart));
        }else {
            img_heart.setBackground(getDrawable(R.mipmap.praisetoicon));
        }
        this.user_id = user_id;
        index_video_id.setText("" + id);
        commentNumber = comments;
        title_introduce.setText(title);
        text_heartNum.setText("" + likes);
        text_commentNum.setText("" + comments);
        text_shareNum.setText("" + shares);
        Uri uri = Uri.parse(url);
        index_video.setVideoURI(uri);
        index_video.start();
        index_video_cover.setVisibility(View.GONE);
        index_video.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
                index_video.stopPlayback(); //播放异常，则停止播放，防止弹窗使界面阻塞
                Toast.makeText(IndexActivity.this,"不支持当前格式",Toast.LENGTH_SHORT).show();
                return true;
            }
        });

//        if (commission == 1){
//            text_commission.setVisibility(View.INVISIBLE);
//            text_commission_logo.setVisibility(View.INVISIBLE);
//            index_want_go.setText("发表评论");
//        }else if(commission == 2){
//            text_commission.setVisibility(View.VISIBLE);
//            text_commission_logo.setVisibility(View.VISIBLE);
//            index_want_go.setText("想去这里");
//        }
    }

    /**
     * 上滑
     */
    private void slideDown() {
        index --;
        if (index >= 0){
            getVideo(index);
            if(attractions_id != -1){
                getParentComment(attractions_id);
            }
        }else {
            index ++;
        }

    }

    /**
     * 下滑
     */
    private void slideUp() {
        index ++;
        if(index < videoList.size()){
            getVideo(index);
            if(attractions_id != -1){
                getParentComment(attractions_id);
            }
        }else {
            index --;
        }
    }

    private void init()  {
        index_video = findViewById(R.id.index_video);
        index_video_id = findViewById(R.id.index_video_id);
        index_music = findViewById(R.id.index_music);
        Intent intent = getIntent();
        String userInfo = intent.getStringExtra("userInfo");
        System.out.println(userInfo);
        getVideoList(1);
        Animation animation = AnimationUtils.loadAnimation(this, R.anim.img_range);
        LinearInterpolator linearInterpolator = new LinearInterpolator();
        animation.setInterpolator(linearInterpolator);
        index_music.startAnimation(animation);
        if(videoList != null && videoList.size() != 0){
            getVideo(0);
            if(attractions_id != -1){
                getParentComment(attractions_id);
            }
        }

    }

    /**
     * 获取视频列表
     * @param type 视频类型（默认1），1：推荐视频、2：关注视频
     */
    private void getVideoList(int type){
        index_loading = findViewById(R.id.index_loading);
        VerticalViewPager video_view_page = findViewById(R.id.video_view_page);
        RelativeLayout index_main = findViewById(R.id.index_main);
        String url = UrlUtil.URL + "/video/info?type=" + type;
        RequestQueue requestQueue= Volley.newRequestQueue(IndexActivity.this);
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                try {
                    videoList = null;
                    Map<String, Object> map = JsonUtil.jsonToMap(s);
                    Integer code = (Integer) map.get("code");
                    if (code == 0) {
                        System.out.println(map.get("data").toString());
                        ArrayList<Video> videos = new ArrayList<>();
                        if(map.get("data").toString().equals("[]")){
                            index_main.setBackground(getDrawable(R.drawable.back));
                            Toast.makeText(IndexActivity.this,"暂无视频列表，快去发布一个吧",Toast.LENGTH_SHORT).show();
                            index_loading.setVisibility(View.INVISIBLE);
                        }else {
                            index_main.setBackgroundResource(0);
                            Map<String,Object> dataMap = (Map<String, Object>) map.get("data");
                            videoList = (ArrayList<Map<String, Object>>) dataMap.get("data");
                            for (int i = 0; i < videoList.size(); i++) {
                                Video video = new Video();
                                String url1 = (String) videoList.get(i).get("url");
                                String cover = (String) videoList.get(i).get("cover");
                                Integer id = (Integer) videoList.get(i).get("id");
                                Integer user_id = (Integer) videoList.get(i).get("user_id");
                                Integer attractions_id = (Integer) videoList.get(i).get("attractions_id");
                                String title = (String) videoList.get(i).get("title");
                                Integer likes = (Integer) videoList.get(i).get("likes");
                                Integer comments = (Integer) videoList.get(i).get("comments");
                                Integer shares = (Integer) videoList.get(i).get("shares");
                                Integer commission = (Integer) videoList.get(i).get("commission");
                                String remark = (String) videoList.get(i).get("remark");
                                String province = (String) videoList.get(i).get("province");
                                String city = (String) videoList.get(i).get("city");
                                Boolean is_likes = (Boolean) videoList.get(i).get("is_likes");
                                Boolean is_attention = (Boolean) videoList.get(i).get("is_attention");
                                Map<String,Object> aPublic = (Map<String, Object>) videoList.get(i).get("publish");
                                String nickname = (String) aPublic.get("nickname");
                                String avatar = UrlUtil.URL +  (String) aPublic.get("avatar");
                                String signature = (String) aPublic.get("signature");
                                video.setUrl(url1);
                                video.setCover(cover);
                                video.setId(id);
                                video.setUserId(user_id);
                                video.setAttractionsId(attractions_id);
                                video.setTitle(title);
                                video.setLikes(likes);
                                video.setComments(comments);
                                video.setShares(shares);
                                video.setCommission(commission);
                                video.setIs_likes(is_likes);
                                video.setIs_attention(is_attention);
                                video.setNickname(nickname);
                                video.setAvatar(avatar);
                                videos.add(video);
                            }
                            if (videoList == null){
                                Toast.makeText(IndexActivity.this,"暂无视频列表，快去发布一个吧",Toast.LENGTH_SHORT).show();
                                index_loading.setVisibility(View.INVISIBLE);
                            }else {
                                video_view_page.setCurrentItem(0);
                                video_view_page.setOffscreenPageLimit(2);
                                video_view_page.setAdapter(new MyViewPagerAdapter(IndexActivity.this,videos));
//                            getVideo(0);
                                index_loading.setVisibility(View.INVISIBLE);
                                Log.i(TAG,videoList.toString());
                            }
                        }
                    } else if(code == -1){
                        Toast.makeText(IndexActivity.this, "登录失效，请重新登录", Toast.LENGTH_LONG).show();
                        Intent intent = new Intent(IndexActivity.this, GetPhoneCodeActivity.class);
                        intent.putExtra("loginCode","-1");
                        startActivity(intent);
                        finish();
                    }else {
                        Object message = map.get("message");
                        Toast.makeText(IndexActivity.this, message.toString(), Toast.LENGTH_SHORT).show();
                        overridePendingTransition(R.anim.xpage_slide_in_left, R.anim.xpage_slide_out_right);
                        finish();
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Log.e(TAG, volleyError.getMessage(), volleyError);
            }
        }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                String sesseionid = new ConnectViaSession(IndexActivity.this).GetSession();
                if (!sesseionid.equals("")) {
                    HashMap<String, String> headers = new HashMap<String, String>();
                    headers.put("cookie", sesseionid);
                    return headers;
                } else {
                    return super.getHeaders();
                }
            }
        };

        requestQueue.add(stringRequest);
    }

    /**
     * 返回事件
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exit();
            return false;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }


    public void exit(){
        if (!isExit) {
            isExit = true;
            Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
            mHandler.sendEmptyMessageDelayed(0, 2000);
        } else {
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_HOME);
            startActivity(intent);
            System.exit(0);
        }
    }


    Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            super.handleMessage(msg);
            isExit = false;
        }

    };



    @Override
    protected void onStart() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            //不加这个clearFlags好像就没效果
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.getDecorView().setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                            | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            //设置导航栏透明(就是虚拟键那一栏)
             
            //设置状态栏(或者叫通知栏)透明
            window.setStatusBarColor(Color.TRANSPARENT);
        }
        super.onStart();
    }

    /**
     * 点赞
     */
    private void faublous() {
        img_heart = findViewById(R.id.img_heart);
        img_heart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                if(img_heart.getBackground().getConstantState().equals(getDrawable(R.mipmap.smallheart).getConstantState())){
//                    img_heart.setBackground(getDrawable(R.mipmap.praisetoicon));
//                }else {
                    if(videoList != null ){
                        if(videoList.size() == 0){
                            Toast.makeText(IndexActivity.this,"未获取视频",Toast.LENGTH_SHORT).show();
                        }else {
                            if(img_heart.getBackground().getConstantState().equals(getDrawable(R.mipmap.praisetoicon).getConstantState())){
                                Integer id = (Integer) videoList.get(index).get("id");
                                videoFablous(id);
                            }
                        }
                    }
                }
//            }
        });
    }

    /**
     * 视频点赞
     * @param id
     */
    private void videoFablous(Integer id) {
        TextView text_heartNum = findViewById(R.id.text_heartNum);
        String url = UrlUtil.URL + "/user/give/likes";
        RequestQueue requestQueue= Volley.newRequestQueue(IndexActivity.this);
        StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                try {
                    Map<String, Object> map = JsonUtil.jsonToMap(s);
                    Integer code = (Integer) map.get("code");
                    if (code == 0) {
                        Toast.makeText(IndexActivity.this, "点赞成功", Toast.LENGTH_LONG).show();
                        String trim = text_heartNum.getText().toString().trim();
                        text_heartNum.setText("" + (Integer.parseInt(trim) + 1));
                        img_heart.setBackground(getDrawable(R.mipmap.smallheart));
                    } else if(code == -1){
                        Toast.makeText(IndexActivity.this, "登录失效，请重新登录", Toast.LENGTH_LONG).show();
                        Intent intent = new Intent(IndexActivity.this, GetPhoneCodeActivity.class);
                        intent.putExtra("loginCode","-1");
                        startActivity(intent);
                        finish();
                    }else {
                        Object message = map.get("message");
                        Toast.makeText(IndexActivity.this, message.toString(), Toast.LENGTH_SHORT).show();
                        overridePendingTransition(R.anim.xpage_slide_in_left, R.anim.xpage_slide_out_right);
                        finish();
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Log.e(TAG, volleyError.getMessage(), volleyError);
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<>();
                map.put("videos_id",String.valueOf(id));
                return map;
            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                String sesseionid = new ConnectViaSession(IndexActivity.this).GetSession();
                if (!sesseionid.equals("")) {
                    HashMap<String, String> headers = new HashMap<String, String>();
                    headers.put("cookie", sesseionid);
                    return headers;
                } else {
                    return super.getHeaders();
                }
            }
        };

        requestQueue.add(stringRequest);
    }

    private void imageHead() {
        img_head = findViewById(R.id.img_head);
        img_head.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(IndexActivity.this, HomePageActivity.class);
                intent.putExtra("user_id","" + user_id);
                intent.putExtra("is_attention",is_attention);
                startActivity(intent);
            }
        });
    }

    private void indexMyInformation() {

        index_my_information = findViewById(R.id.index_my_information);
        index_my_information.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(IndexActivity.this, MyInfoActivity.class));
                
            }
        });
    }

    private void indexMyCommission() {

        index_my_commission = findViewById(R.id.index_my_commission);
        index_my_commission.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(IndexActivity.this, CommissionRankActivity.class));
                
            }
        });
    }

    private void indexWantGo() {
        EditText index_comment = findViewById(R.id.index_comment);
        index_want_go = findViewById(R.id.index_want_go);
        index_want_go.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String want_go_name = index_want_go.getText().toString().trim();
                if(want_go_name.equals("发表评论")){
                    String commenContent = index_comment.getText().toString().trim();
                    if(!commenContent.equals("")){
                        sendComment(commenContent);
                    }else {
                        Toast.makeText(IndexActivity.this,"请输入评论内容",Toast.LENGTH_SHORT).show();
                    }

                }else {
                    Intent intent = new Intent(IndexActivity.this, ScreenDetailsActivity.class);
//                    intent.putExtra("attractions_id",attractions_id);
                    intent.putExtra("attractions_id",1);
                    startActivity(intent);
                }


            }
        });
    }

    /**
     * 视频的评论列表
     */

    private void getParentComment(int id){
        ArrayList<Comment> comments = new ArrayList<>();
        String url = UrlUtil.URL + "/user/comments/videos/list?vid=" + id;
        RequestQueue requestQueue= Volley.newRequestQueue(IndexActivity.this);
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                try {
                    Map<String, Object> map = JsonUtil.jsonToMap(s);
                    Integer code = (Integer) map.get("code");
                    if (code == 0) {
                        Map<String,Object> data = (Map<String, Object>) map.get("data");
                        Log.i(TAG,data.toString());
                        List<Map<String, Object>> mapList = (List<Map<String, Object>>) data.get("data");
                        Log.i(TAG,mapList.toString());
                        for (int i = 0; i < mapList.size(); i++) {
                            Comment comment = new Comment();
                            Integer id1 = (Integer) mapList.get(i).get("id");
                            Integer user_id = (Integer) mapList.get(i).get("user_id");
                            Integer video_id = (Integer) mapList.get(i).get("video_id");
                            Integer parent = (Integer) mapList.get(i).get("parent");
                            String user_nickname = (String) mapList.get(i).get("user_nickname");
                            String user_avatar = (String) mapList.get(i).get("user_avatar");
                            String content = (String) mapList.get(i).get("content");
                            String  picture = (String) mapList.get(i).get("picture");
                            String  created_at = (String) mapList.get(i).get("created_at");
                            Integer likes = (Integer) mapList.get(i).get("likes");
                            comment.setTime(created_at);
                            comment.setId(id1);
                            comment.setTitle(user_nickname);
                            comment.setMessage(content);
                            comment.setHead(UrlUtil.URL + user_avatar);
                            getChildComment(id1);
                            comment.setComments(childComments);
                            comments.add(comment);

                        }
                        parentComment = comments;

                    } else if(code == -1){
                        Toast.makeText(IndexActivity.this, "登录失效，请重新登录", Toast.LENGTH_LONG).show();
                        Intent intent = new Intent(IndexActivity.this, GetPhoneCodeActivity.class);
                        intent.putExtra("loginCode","-1");
                        startActivity(intent);
                        finish();
                    }else {
                        Object message = map.get("message");
                        Toast.makeText(IndexActivity.this, message.toString(), Toast.LENGTH_SHORT).show();
                        overridePendingTransition(R.anim.xpage_slide_in_left, R.anim.xpage_slide_out_right);
                        finish();
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Log.e(TAG, volleyError.getMessage(), volleyError);
            }
        }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                String sesseionid = new ConnectViaSession(IndexActivity.this).GetSession();
                if (!sesseionid.equals("")) {
                    HashMap<String, String> headers = new HashMap<String, String>();
                    headers.put("cookie", sesseionid);
                    return headers;
                } else {
                    return super.getHeaders();
                }
            }
        };

        requestQueue.add(stringRequest);

    }

    /**
     * 视频的子评论列表
     */

    private void getChildComment(int pid){
        ArrayList<Comment> comments = new ArrayList<>();
        String url = UrlUtil.URL + "/user/comments/videos/child?pid=" + pid;
        RequestQueue requestQueue= Volley.newRequestQueue(IndexActivity.this);
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                try {
                    Map<String, Object> map = JsonUtil.jsonToMap(s);
                    Integer code = (Integer) map.get("code");
                    if (code == 0) {
                        Map<String,Object> data = (Map<String, Object>) map.get("data");
                        Log.i(TAG,data.toString());
                        List<Map<String, Object>> mapList = (List<Map<String, Object>>) data.get("data");
                        Log.i(TAG,mapList.toString());
                        for (int i = 0; i < mapList.size(); i++) {
                            Comment comment = new Comment();
                            Integer id1 = (Integer) mapList.get(i).get("id");
                            Integer user_id = (Integer) mapList.get(i).get("user_id");
                            Integer video_id = (Integer) mapList.get(i).get("video_id");
                            Integer parent = (Integer) mapList.get(i).get("parent");
                            String user_nickname = (String) mapList.get(i).get("user_nickname");
                            String user_avatar = (String) mapList.get(i).get("user_avatar");
                            String content = (String) mapList.get(i).get("content");
                            String  picture = (String) mapList.get(i).get("picture");
                            String  created_at = (String) mapList.get(i).get("created_at");
                            Integer likes = (Integer) mapList.get(i).get("likes");
                            comment.setTime(created_at);
                            comment.setId(id1);
                            comment.setTitle(user_nickname);
                            comment.setMessage(content);
                            comment.setHead(UrlUtil.URL  + user_avatar);
                            comments.add(comment);

                        }
                        childComments = comments;

                    } else if(code == -1){
                        Toast.makeText(IndexActivity.this, "登录失效，请重新登录", Toast.LENGTH_LONG).show();
                        Intent intent = new Intent(IndexActivity.this, GetPhoneCodeActivity.class);
                        intent.putExtra("loginCode","-1");
                        startActivity(intent);
                        finish();
                    }else {
                        Object message = map.get("message");
                        Toast.makeText(IndexActivity.this, message.toString(), Toast.LENGTH_SHORT).show();
                        overridePendingTransition(R.anim.xpage_slide_in_left, R.anim.xpage_slide_out_right);
                        finish();
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Log.e(TAG, volleyError.getMessage(), volleyError);
            }
        }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                String sesseionid = new ConnectViaSession(IndexActivity.this).GetSession();
                if (!sesseionid.equals("")) {
                    HashMap<String, String> headers = new HashMap<String, String>();
                    headers.put("cookie", sesseionid);
                    return headers;
                } else {
                    return super.getHeaders();
                }
            }
        };

        requestQueue.add(stringRequest);
    }

    String[] permissions = new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
    List<String> mPermissionList = new ArrayList<>();

    // private ImageView welcomeImg = null;
    private static final int PERMISSION_REQUEST = 1;
    // 检查权限

    private void checkPermission() {
        mPermissionList.clear();

        //判断哪些权限未授予
        for (int i = 0; i < permissions.length; i++) {
            if (ContextCompat.checkSelfPermission(this, permissions[i]) != PackageManager.PERMISSION_GRANTED) {
                mPermissionList.add(permissions[i]);
            }
        }
        /**
         * 判断是否为空
         */
        if (mPermissionList.isEmpty()) {//未授予的权限为空，表示都授予了

        } else {//请求权限方法
            String[] permissions = mPermissionList.toArray(new String[mPermissionList.size()]);//将List转为数组
            ActivityCompat.requestPermissions(IndexActivity.this, permissions, PERMISSION_REQUEST);
        }
    }

    /**
     * 响应授权
     * 这里不管用户是否拒绝，都进入首页，不再重复申请权限
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case PERMISSION_REQUEST:

                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
                break;
        }
    }


    private void ShareVideo(){
        img_share = findViewById(R.id.img_share);
        img_share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               ShareVideoPath();
            }
        });
    }

    private void ShareVideoPath() {
        Intent intent = new Intent( Intent.ACTION_SEND);
        intent.setType( "text/plain");
        intent.putExtra(Intent.EXTRA_TEXT, videoUrl);
        startActivity(Intent.createChooser(intent, "分享视频地址到..."));
    }


}
